<template>
    <div>
        <a-modal
         v-model:visible="visible" 
         :title="formState.id?(formState.view?'查看':'编辑'):'新增'"  
         @ok="handleOk" 
         @cancel="visible = false"
         class="enterprise-add-edit-modal"
         width="100%"
         wrapClassName="full-modal"
         :footer="null"
        >
            <div v-if="visible">
                <a-form :form="form" layout="horizontal" class="add-edit-form">
                    <a-form-item label="物料目录">
                        <a-select
                            ref="select"
                            placeholder="请选择物料目录"
                            @change="getDealer($event,true)"
                            v-decorator="[
                                'fwlmlid', { initialValue:formState.fwlmlid, rules: rules.fwlmlid}
                            ]"
                            >
                            <a-select-option v-for="(item,index) in materialClassList" :value="item.id">{{ item.fwlmc }}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="经销商名称" v-if="formState.fwlmlid">
                        <a-select
                            ref="select"
                            placeholder="请选择经销商名称"
                            @change="fwlsjidChange"
                            v-decorator="[
                                'fwlsjid', { initialValue:formState.fwlsjid, rules: rules.fwlsjid}
                            ]"
                            >
                            <a-select-option v-for="(item,index) in dealerList" :value="item.id">{{ item.fjxsmc }}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="预警值" v-if="formState.fwlsjid">{{ formState.sfgq }}</a-form-item>
                    <a-form-item label="入库批号">
                        <a-input
                        v-model:value="formState.frkph"
                        placeholder="请输入入库批号"
                        v-decorator="[
                            'frkph', { initialValue:formState.frkph, rules: rules.frkph}
                        ]"/>
                    </a-form-item>
                    <a-form-item label="库存数量">
                        <a-input-number
                        style="width: 185px;"
                        :min="0"
                        :precision="0"
                        v-model:value="formState.fkcsl"
                        placeholder="请输入库存数量"
                        v-decorator="[
                            'fkcsl', { initialValue:formState.fkcsl, rules: rules.fkcsl}
                        ]"/>
                    </a-form-item>
                    <a-form-item label="库存有效期" class="flex-1-box">
                        <span v-if="formState.fyxq == '长期有效'">{{ formState.fyxq }}</span>
                        <a-date-picker
                        v-else
                        v-model:value="formState.fyxq"
                        placeholder="请选择库存有效期"
                        v-decorator="[
                            'fyxq', { initialValue:formState.fyxq, rules: rules.fyxq}
                        ]"/>
                        <a-button style="margin-left: 5px;" v-if="formState.fyxq !== '长期有效'" class="blue-btn" type="primary" @click="formState.fyxq = '长期有效'"> 长期有效 </a-button>
                    </a-form-item>
                    
                    <div style="width: 100%;">
                        <table border="1" class="material-table">
                            <tr>
                                <th style="text-align: center;padding: 5px;">文件目录</th>
                                <th style="text-align: center;padding: 5px;">文件清单</th>
                                <th style="text-align: center;padding: 5px;">操作 <span style="color: red;font-size: 12px;">（提示：批量上传文件放在同一个文件夹内，选择文件夹上传）</span></th>
                            </tr>
                            <tr v-for="(item,index) in fjxxList" :key="index">
                                <td style="width: 30%;text-align: center;">{{ item.wjml }}</td>
                                <td style="width: 50%;">
                                    <div style="display: flex;width: 100%;flex-wrap: wrap;">
                                        <div class="file-td-box" v-for="(term,tIndex) in item.wjList">
                                            <a-icon class="delete-icon-v" type="delete" @click="deleteClick(term)" v-if="!formState.view"/>
                                            <a-icon class="eye-icon-v" type="eye" @click="viewClick(term)" v-if="term.fwjlx == '.pdf'"/>
                                            <a-icon class="download-icon-v" type="download" @click="downloadClick(term)"/>
                                            <a-icon class="file-icon-v" type="file-pdf" />
                                            <span>{{ term.fwjxsmc+term.fwjlx }}</span>
                                        </div>
                                    </div>
                                </td>
                                <td style="width: 20%;">
                                    <div style="display: flex;justify-content: center;padding: 5px;" v-if="!formState.view">
                                        <a-upload :disabled="uploadLoading"
                                        v-if="formState.id"
                                        style="display: inline-block;" 
                                        :beforeUpload="enterpriseBeforeUpload" 
                                        action="" 
                                        @change="enterpriseUpload($event,item)">
                                            <a-button :loading="uploadLoading" style="margin-right: 15px;" class="blue-btn" type="primary" @click="uploadSave">上传</a-button>
                                        </a-upload>
                                        <a-button v-else style="margin-right: 15px;" class="blue-btn" type="primary" @click="handleOk(true)">上传</a-button>
                                        <a-upload :disabled="uploadLoading"
                                        v-if="formState.id"
                                        style="display: inline-block;" 
                                        :beforeUpload="enterpriseBeforeUpload" 
                                        action="" 
                                        @change="enterpriseUpload($event,item)" directory>
                                            <a-button :loading="uploadLoading" class="blue-btn" type="primary" @click="uploadSave">批量上传</a-button>
                                        </a-upload>
                                        <a-button v-else class="blue-btn" type="primary" @click="handleOk(true)">批量上传</a-button>
                                    </div>
                                    
                                </td>
                            </tr>
                        </table>
                    </div>
                </a-form>
            </div>
            <div style="
                display: flex; justify-content: flex-end;
                margin-top: 20px; width: 100%;
                position: absolute; left: 0;
                bottom: 0; padding: 18px 24px;
                background-color: #fff;">
                <a-button @click="visible = false">取消</a-button>
                <a-button v-if="!formState.view" style="margin: 0 20px;" class="blue-btn" type="primary" @click="handleOk(true)">保存</a-button>
                <a-button v-if="!formState.view" class="blue-btn" type="primary" @click="handleOk(false)">保存并关闭</a-button>
            </div>
            <serverEditingView ref="serverEditingViewRef" @refreshChange="$event=>{}"/>
        </a-modal>
    </div>
</template>
<script>
import compSelector from '@/components/compSelector/compSelector.vue'
import serverEditingView from '@/components/comp-model-series/server-editing-view'
import moment from 'moment'
import YchConstant from "@/api/YchConstant";
import blobType from '@/common/blobType'
import { 
    spcyQyInfoqueryWlkcWjml, 
    spcyQyInfoUploadMoreTypeFile, 
    getFileTypeServe, 
    deleteFileById, 
    getCrossLocalFile, 
    spcyQyInfoqueryGyssjByWlIdList,
    spcyQyInfoqueryAllWlmlList,
} from '../service/index'
export default {
    components:{
        serverEditingView,
        compSelector,
    },
    props:{

    },
    data(){
        return{
            visible:false,
            formState:{},
            form: this.$form.createForm(this, { name: 'coordinated' }),
            rules:{
                fwlmlid: [{
                    required: true,
                    message: '请输入物料目录',
                    trigger: 'blur',
                }],
                fwlsjid: [{
                    required: true,
                    message: '请选择经销商名称',
                    trigger: 'blur',
                }],
                frkph: [{
                    required: true,
                    message: '请输入入库批号',
                    trigger: 'blur',
                }],
                fkcsl: [{
                    type:'number',
                    required: true,
                    message: '请输入库存数量',
                    trigger: 'blur',
                }],
                fyxq: [{
                    type:'object',
                    required: true,
                    message: '请选择库存有效期',
                    trigger: 'blur',
                }],
            },
            fjxxList:[],
            uploadLoading:false,
            dealerList:[],
            materialClassList:[],
        }
    },
    watch:{

    },
    mounted(){
    },
    methods:{
        getData(val){
            this.formState = {}
            this.formState = {...val,forder:val.forder?val.forder:1}
            this.formState.fyxq = val.fyxq?(val.fyxq == '长期有效'?val.fyxq:moment(val.fyxq)):''
            this.getFile(val)
            this.dealerList = []
            this.materialClassList = []
            //经销商查询
            if(this.formState.fwlmlid){
                this.getDealer(this.formState.fwlmlid,true)
            }
            
            //查询物料分类
            spcyQyInfoqueryAllWlmlList({fqyid:this.formState.fqyid}).then(res=>{
                if(res.code == 200){
                    //console.log('物料分类',res)
                    this.materialClassList = res.result
                }else{
                    this.$message.warning(res.message)
                }
            })
        },
        getDealer(val,isNull){
            //console.log(val)
            this.formState.fwlmlid = val
            spcyQyInfoqueryGyssjByWlIdList({fwlmlid:this.formState.fwlmlid}).then(res=>{
                if(res.code == 200){
                    //console.log('经销商',res)
                    this.dealerList = res.result
                    // if(!isNull){
                        this.formState.fwlsjid = undefined
                        this.form.setFieldsValue({
                            fwlsjid:undefined
                        });
                    // }else{
                    //     this.getsfgq(this.formState.fwlsjid)
                    // }
                    
                }else{
                    this.$message.warning(res.message)
                    
                }
            })
        },
        fwlsjidChange(val){
            //console.log(val)
            this.formState.fwlsjid = val
            this.form.setFieldsValue({
                fwlsjid:val
            });
            this.getsfgq(val)
        },
        getsfgq(val){
            this.dealerList.forEach(item => {
                if(item.id == val){
                    this.formState.sfgq = item.sfgq
                }
            });
        },
        forderChange(val){
            //console.log(val)
            if(!val){
                this.formState.forder = 1
            }
        },
        getFile(val){
            spcyQyInfoqueryWlkcWjml({id:val.id?val.id:''}).then(res=>{
                if(res.code == 200){
                    this.fjxxList = res.result
                }else{
                    this.$message.warning(res.message)
                }
            })
        },
        deleteClick(val){
            var that = this
            this.$confirm({
                title:'您确认要删除吗？',
                // icon: createVNode(ExclamationCircleOutlined),
                onOk() {
                    deleteFileById({id:val.id}).then(res=>{
                        if(res.code == 200){
                            that.$message.success('删除成功')
                            that.getFile(that.formState)
                        }else{
                            that.$message.warning(res.message)
                        }
                    })
                },
                
            });
        },
        viewClick(val){
            this.$refs.serverEditingViewRef.getData({id:val.id,fwjlx:val.fwjlx,type:'企业信息'})
            this.$refs.serverEditingViewRef.serverEditingVisible = true
        },
        lookOverClick(val){
            getFileTypeServe({id:val.id}).then(res=>{
                if(res.code == 200){
                    if(res.result == '.pdf'){
                        window.open(
                            bootConfig[process.env.NODE_ENV].locality_ApI+YchConstant.SPZX_SPCY+'/spcySqsxWjjl/getCrossLocalFile?id='+val.id
                        )
                    }else{
                        this.$message.warning('只能查看pdf文件')
                    }
                    
                }
                
            })
        },
        downloadClick(val){
            
            var that = this
            var fileName = val.fwjxsmc
            let param = {id:val.id}
            getFileTypeServe({id:val.id}).then(res=>{
                if(res.code == 200){
                    getCrossLocalFile(param).then((data) => {
                        if (!data) {
                            that.$message.warning('文件下载失败')
                            return
                        }else{
                        // if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //     window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }))
                        // } else {
                            let url = window.URL.createObjectURL(new Blob([data], { type: blobType.type[blobType.suffix.indexOf(val.fwjlx)] }))
                            let link = document.createElement('a')
                            link.style.display = 'none'
                            link.href = url
                            link.setAttribute('download', fileName + res.result)
                            document.body.appendChild(link)
                            link.click()
                            document.body.removeChild(link) //下载完成移除元素
                            window.URL.revokeObjectURL(url) //释放掉blob对象
                        // }
                        }
                    })
                }
                
            })
        },
        enterpriseBeforeUpload(e){
            return false
        },
        uploadSave(){
            if(!this.formState.id){
                this.handleOk(true,true)
            }
        },
        enterpriseUpload({file},val){//
            var that = this
            this.uploadLoading = true
            if(typeof file.uid !== 'undefined') {
                // if(file.name.indexOf(".xls") !== -1 || file.name.indexOf(".xlsx") !==-1) {
                    const fileData = new FormData();
                    fileData.append("file",file);
                    fileData.append("id",this.formState.id);
                    fileData.append("fwjlx1",val.wjml);
                    
                    spcyQyInfoUploadMoreTypeFile(fileData).then(res => {
                        if(res.code){
                            if(res.code == 200){
                                this.uploadLoading = false
                                that.$message.success(res.message)
                            }else{
                                this.uploadLoading = false
                                that.$message.warning(res.message)
                            }
                            
                        }
                        if(res.byteLength){
                            if(res.code && res.code !== 200){
                                this.uploadLoading = false
                                that.$message.warning('请上传对应文件类型或者联系管理员!')
                            }else{
                                this.uploadLoading = false
                                that.$message.success('上传成功')
                            }
                        }
                        this.getFile(this.formState)
                    })
                // }
                
            }
        },
        handleOk(val){
            this.form.validateFields((err, values) => {
                if (!err) {
                    if(this.formState.id){
                        this.$emit('editItem',{
                            ...this.formState,
                            ...values,
                            fyxq:this.formState.fyxq?(this.formState.fyxq == '长期有效'?this.formState.fyxq:moment(this.formState.fyxq).format('YYYY-MM-DD')):''
                        },val)
                    }else{
                        this.$emit('addItem',{
                            ...this.formState,
                            ...values,
                            fyxq:this.formState.fyxq?(this.formState.fyxq == '长期有效'?this.formState.fyxq:moment(this.formState.fyxq).format('YYYY-MM-DD')):''
                        },val)
                    }
                    
                }
            })
        },
    }
}
</script>
<style lang="less">
.enterprise-add-edit-modal{
    .add-edit-form{
        display: flex;
        flex-wrap: wrap;
        .ant-form-item{
            display: flex;
        }
        .ant-form-item-label{
            width: 130px;
        }
        .ant-form-item-control-wrapper{
            width: 180px;
        }
        .flex-1-box{
            width: 100%;
            .ant-form-item-control-wrapper{
                flex: 1;
            }
        }
    }
    .material-table{
        width: 100%;
        border-color: #d9d9d9 !important;
    }
}
.file-td-box{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-content: space-between;
    width: 104px;
    height: 104px;
    overflow: hidden;
    border-radius: 2px;
    border: 1px solid #d9d9d9;
    padding: 8px;
    margin: 8px;
    position: relative;
    .delete-icon-v{
        font-size: 16px;
        position: absolute;
        color: #ed5565;
        left: -60px;
        top: 3px;
    }
    .eye-icon-v{
        font-size: 16px;
        position: absolute;
        color: rgb(24, 144, 255);
        right: 11px;
        top: 38px;
    }
    .download-icon-v{
        width: 20px;
        font-size: 16px;
        position: absolute;
        color: rgb(24, 144, 255);
        right: 9px;
        top: 5px;
    }
    .download-icon-apply{
        top: 10px;
    }
    .fjbz-text-v{
        color: #ff8000;
        font-size: 12px !important;
        display: inline-block;
        width: 28px;
        position: absolute;
        top: 5px;
        left: 3px;
    }
    .file-icon-v{
        font-size: 42px;
        color: rgb(24, 144, 255);
    }
    .file-icon-v{
        font-size: 42px;
        color: rgb(24, 144, 255);
    }
    span{
        height: 40px;
        display:block;
        text-overflow: -o-ellipsis-lastline;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        font-size: 14px;
    }
}
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}
.ant-upload-list{
    display: none;
}
.ant-upload-list-item{
    display: none !important;
}
</style>